import React, { useState, useMemo, useEffect, useRef, useCallback } from 'react';
import './sku.scss';
import Price from '@/components/price';
import SkuSelect from './sku-select';
import { Image } from 'antd-mobile'
import SkuOperate from './SkuOperate';
import SkuStepper from './SkuStepper';
import { SkuInfo, BtnOptionsItem, SelectedSkuType, OptionItemType, GoodsInfoType } from './typing';
import { bem, isEmpty, genUUID } from '@/utils';

export interface SkuProps {
    isMainSku?: boolean;
    unit?: string;
    selectedSku?: SelectedSkuType,
    goods?: GoodsInfoType,
    onUpdateSelectedSku: (value: SelectedSkuType) => void;
    onAdd?: (value: number) => void;
    onReduce?: (value: number) => void;
    onChangeStepper?: (value: number) => void;
    onConfirm?: (selectedSku: SelectedSkuType) => void;
}

const defaultProps = {
    unit: '个',
    selectedSku: {},
    btnOptions: [
        {
            btnId: 'cart',
            btnTitle: '加入购物车',
            btnClassName: 'cart'
        },
        {
            btnId: 'buy',
            btnTitle: '立即购买',
            btnClassName: 'buy'
        }
    ]
}

const mergeSkuSpecsData = (skuSpecs?: Array<SkuInfo>): Array<SkuInfo> => {
    const newSkuSpecs = skuSpecs || [];
    if (isEmpty(skuSpecs)) {
        newSkuSpecs.push({
            attrId: genUUID(),
            attrName: '规格',
            optionList: [
                {
                    id: -1,
                    name: '默认',
                    active: true,
                    disable: false,
                }
            ]
        });
    }
    return newSkuSpecs;
};


const SkuComponent: React.FC<SkuProps> = (props) => {
    const {
        goods,
        selectedSku,
        btnOptions,
        isMainSku,
        unit,
        onUpdateSelectedSku,
        onAdd,
        onReduce,
        onConfirm,
        onChangeStepper,
        ...rest
    } = {
        ...defaultProps,
        ...props
    }

    if (isEmpty(goods) || isEmpty(goods?.sku)) {
        console.error('goods is empty');
        return;
    }
    const b = bem('sku');

    const { skuList, skuSpecs } = goods?.sku || {};
    /**
    * 用于保存组件是否被卸载的状态的引用
    * @type {React.MutableRefObject<boolean>}
    */
    const unMountRef = useRef<boolean>(false);
    const [skuSpecsData, setSkuSpecsData] = useState<Array<SkuInfo>>(mergeSkuSpecsData(skuSpecs));
    const [quantity, setQuantity] = useState(1);

    const skuLisMap = (): Map<string, any> => {
        const map = new Map<string, any>();
        if (skuList) {
            for (let i = 0; i < skuList.length; i++) {
                const sku = skuList[i];
                const key = String(sku.aps || '-1');
                map.set(key, sku);
            }
        }
        return map;
    };

    // 使用useMemo优化选中状态计算（不包含数量）
    const skuSelection = useMemo<SelectedSkuType>(() => {
        if (isEmpty(skuSpecsData)) {
            return {} as SelectedSkuType;
        }
        const selectedProps: OptionItemType[] = [];
        const skuGroupNum = skuSpecsData.length;
        let selectedNum = 0;

        // 初始化默认SKU信息
        const skuGoods = {
            skuName: goods?.goodsName,
            skuId: 0,
            skuImage: goods?.mainImage,
            skuPrice: goods?.goodsPrice,
            stock: 0,
            isSelected: false
        } as SelectedSkuType;

        // 收集已选属性
        skuSpecsData.forEach(spec => {
            const selectedOption = spec.optionList.find(option => option.active);
            if (selectedOption) {
                selectedProps.push(selectedOption);
                selectedNum++;
            }
        });

        // 当所有规格都已选择时，匹配具体SKU
        if (selectedNum === skuGroupNum) {
            const aps = selectedProps.map(prop => prop.id).sort().join(':');
            const matchedSku = skuLisMap().get(aps);
            if (matchedSku) {
                Object.assign(skuGoods, {
                    skuId: matchedSku.skuId,
                    skuName: matchedSku.skuName,
                    skuPrice: matchedSku.skuPrice,
                    skuImage: matchedSku.skuImage,
                    stock: matchedSku.stock || 0,
                    isSelected: true,
                });
            } else {
                console.warn('未匹配到SKU数据');
            }
        }
        return {
            ...skuGoods,
            selectedProps,
            selectedNum,
            quantity,
            skuGroupNum,
            isMainSku: (isMainSku ? true : false),
        };
    }, [skuSpecsData, goods, skuList]);

    // 合并数量信息
    const selectedSkuState = useMemo<SelectedSkuType>(() => {
        return {
            ...skuSelection,
            quantity,
        };
    }, [goods, skuSelection, quantity]);

    // 当规格或数量变化时更新父组件
    useEffect(() => {
        if (!isEmpty(skuSelection)) {
            onUpdateSelectedSku?.(selectedSkuState);
        }
    }, [selectedSkuState]);

    const handleSelectSku = useCallback((param: any) => {
        const { option, skuIndex } = param;
        // 如果选项被禁用，则不处理
        if (option.disable) return;
        const newSkuData = skuSpecsData.map((spec, index) => {
            if (index === skuIndex) {
                return {
                    ...spec,
                    optionList: spec.optionList.map(item => ({
                        ...item,
                        active: item.id === option.id
                    }))
                };
            }
            return spec;
        });
        setSkuSpecsData(newSkuData);
    }, [skuSpecsData]);

    const handleClickBtnOperate = (btn: BtnOptionsItem) => {
        if (btn.btnId === 'buy') {
            const newValue = {
                ...selectedSkuState,
                quantity
            };

            onUpdateSelectedSku?.(newValue);
            onConfirm?.(newValue);
            return;
        }
    }

    const handleInputChange = useCallback((value: number) => {
        setQuantity(value);
    }, [quantity]);

    const getSelectedDesc = () => {
        if (isEmpty(selectedSkuState)) {
            return '';
        }
        const { selectedProps } = selectedSkuState;
        if (isEmpty(selectedProps)) return '';
        const propsStr = selectedProps.map(item => item.name).join('，');
        return propsStr + '，' + quantity + unit;
    }

    useEffect(() => {
        unMountRef.current = false;
        return () => {
            unMountRef.current = true;
        };
    }, []);

    return (
        <div className={b()}>
            <div className={b('head')}>
                <div className={b('head-left')}>
                    <Image src={selectedSkuState?.skuImage || ''} lazy />
                </div>
                <div className={b('head-right')}>
                    <div className={b('price')}>
                        <Price price={selectedSkuState?.skuPrice || 0} size='xlarge' />
                        <div className={b('tag-list')}>
                            <div className={b('tag-list-item')}>到手价</div>
                        </div>
                    </div>

                    <div className={b('choose-info')}>
                        <span>已选</span>
                        {getSelectedDesc()}
                    </div>
                </div>
            </div>

            <div className={b('body')}>
                <SkuSelect
                    skuSpecs={skuSpecsData}
                    selectSku={handleSelectSku}
                />

                <SkuStepper
                    value={quantity}
                    onChange={handleInputChange}
                />
            </div>
            {
                btnOptions && btnOptions.length > 0 && (
                    <SkuOperate btnOptions={btnOptions}
                        onClientBtnOperate={handleClickBtnOperate}>

                    </SkuOperate>
                )
            }


        </div>
    );
}


export default SkuComponent;
